package cn.hunqing.web.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.hunqing.web.entity.User;
import cn.hunqing.web.mapper.UserMapper;
import cn.hunqing.web.msg.RegisterMsgs;
import cn.hunqing.web.service.UserService;
import cn.hunqing.web.session.SessionUserInfo;
import cn.hunqing.web.util.LoginIdChecker;

/**
 *
 * @date 2015-08-01 18:13
 */
@Service
public class UserServiceImpl implements UserService {
	private static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

	@Autowired
	private UserMapper userMapper;
	
	@Override
	public SessionUserInfo saveOrUpdate(User user) {
		logger.info("Step1, get the user id by the union id");
		logger.info("saveOrUpdate current user openId is "+ user.getOpenId());
//		Integer userId = userMapper.findByUnionID(user.getUnionId());
		Integer userId = userMapper.findByOpenID(user.getOpenId());
		logger.info("Step2, find by openId "+user.getOpenId()+" the user id is " + userId);
		if(userId == null){
			logger.info("Step2, insert the user info into db.");
			userMapper.insert(user);
		}else{
			logger.info("Step2, update the last login time");
			userMapper.updateLastLoginTime(userId);
			user.setId(userId);
		}
		
		return SessionUserInfo.buildFrom(user);
	}

	@Override
	public void findByUnionID(String unionID) {
	}

	@Override
	public SessionUserInfo findByUserNameAndPassword(String userName, String password) {
		User user = null;
		
		Map<String,String> parameters = new HashMap<>();
//		if (LoginIdChecker.checkEmail(userName)) {
//			parameters.put("email", userName);
//		} else if (LoginIdChecker.checkMobile(userName)) {
//			parameters.put("phone", userName);
//		} else {
			parameters.put("userName", userName);
//		}
		user = userMapper.findByParamters(parameters);
		
		if (user != null) {
			if (StringUtils.equals(DigestUtils.md5Hex(password), user.getPassword())) {
				SessionUserInfo sessionUserInfo = SessionUserInfo.buildFrom(user);

				return sessionUserInfo;
			}
		}
		return null;
	}

	@Transactional
	@Override
	public void register(String userName, String password){

		Map<String,String> parameters = new HashMap<>();
		parameters.put("userName", userName);
		User user = userMapper.findByParamters(parameters);
		
		if(user != null){
			throw new RuntimeException(RegisterMsgs.DUPLICATE_USERNAME);
		}
		
		User newUser = new User();
		newUser.setUserName(userName);
		newUser.setPassword(DigestUtils.md5Hex(password));
		
		userMapper.insert(newUser);
		
		logger.info("Register the user:{} successfully with id:{}",userName,newUser.getId());
	}
}
